<template>
  <div>
    <el-dialog :title="formData.id?'编辑分类':'添加分类'" :visible="showDialog" @close="closeFn">
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="formData.desc" type="textarea" />
        </el-form-item>
        <el-form-item label="封面">
          <!-- 封面图片上传组件 -->
          <UploadImage ref="img" />
          <el-input v-model="coverImgUrl" placeholder="强制设置图片跳过上传" @blur="sendImgUrl" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-row type="flex" justify="end">
          <el-button type="primary" size="small" @click="submit">确定</el-button>
          <el-button size="small" @click="closeFn">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addCategory, getCategoryById, editCategory } from '@/api/category'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      coverImgUrl: '', // 用户输入的封面地址
      formData: {
        title: '', // 标题
        desc: '', // 描述
        image: ''// 封面图
      },
      rules: {
        title: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 传入封面图片地址给UploadImage组件
    sendImgUrl() {
      this.$refs.img.imgUrl = this.coverImgUrl
    },
    // 确认 添加/编辑
    async submit() {
      // 验证通过
      await this.$refs.form.validate()
      //   判断图片是否存在
      if (this.$refs.img.imgUrl) {
        this.formData.image = this.$refs.img.imgUrl
      } else {
        this.formData.image = null
      }
      if (this.formData.id) {
        // 编辑
        await editCategory(this.formData)
      } else {
        // 调用添加分类接口
        await addCategory(this.formData)
      }
      //   重新渲染页面
      this.$emit('updateEvent')
      //   提示用户
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      // 关闭弹窗
      this.closeFn()
    },
    // 关闭弹窗
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空表单数据和校验
      this.formData = {
        title: '', // 标题
        desc: '', // 描述
        image: ''// 封面图
      }
      this.$refs.form.resetFields()
      this.$refs.img.imgUrl = null
    },
    // 实现数据回显
    async getCategoryDate(id) {
      this.formData = await getCategoryById(id)
      // 封面图片回显
      this.$refs.img.imgUrl = this.formData.image
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-textarea__inner{
   resize: none;
    min-height: 96px;
    height: 96px;
}
</style>
